/* eslint-disable react/jsx-handler-names */
/* eslint-disable eqeqeq */
import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, PrimaryGhostC, TableC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import OrderFormC from './orderFormC';
import { uniqueKey, AutomaticSettlement } from '../../../../utils/commonFunc';
import OrderC from '../../../../comps/business/orderC';

class AddOrderC extends PureComponent {
  static defaultProps = {
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };

  state = {
    info: undefined, // 详情
    type: undefined, // 当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情  11-组合试算
    isShow: false, // 二次确认模态框显示隐藏
    querys: {}, // 二次确认详情数据
    isCanOrder: true, // 组合是否可以下达 默认可以
    trailColumns: [], // 试算结果列表
    trailDataSource: [], // 试算结果数据
    trailModel: false, // 试算模态框
    productId: undefined, // 产品code
    portfolioId: undefined, // 组合id
    portfolioCode: undefined,
    uid: '',
    visibleStep: false, // 下达弹窗
    orderParams: undefined, // 下达需要的参数
  };

  componentDidMount() {
    this.props.onRef(this);
    if (this.props.type == 1) {
      // 指令下达 请求
      const uid = uniqueKey();
      uid.then((r) => {
        this.setState({ uid: r });
      });
    }
  }

  // 用户点击下达或确定按钮
  onOk = () => {
    const { type, isStop, position, info } = this.props;
    if (!this.state.isCanOrder && type == 1) {
      // 指令新增
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.orderForm.getInfo();
    // 校验页面数据
    if (!data) return;
    data.id = this.state.uid;

    if (type == 1) {
      // 新增指令
      if (this.state.isShow) {
        this.confirmOk(data); // 二次确认的确定 点击按钮
      } else {
        // 指令下达需要二次确认
        this.setState({
          querys: data,
          isShow: true,
        });
      }
    } else {
      // 簿记无需二次确认 直接请求后端
      this.confirmOk(data);
    }
  };

  // 用户点击取消
  onCancel = () => {
    this.orderForm.reset();
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };

  confirmOk = (params0) => {
    let params = params0;
    // 指令下达 簿记保存请求后台
    const {
      dispatch,
      type,
      user: { currentUser },
    } = this.props;
    console.log(type);
    if (type == 11) {
      // 组合试算
      params = {
        portfolioCode: this.state.portfolioCode,
        productCode: this.state.productId,
        type: '20',
        userId: params.userid,
        userName: params.username,
        businessType: '20',
        tenant: currentUser.tenant, // 租户code
        uid: params.id,
        trade20: {
          ...params,
        },
      };
    }
    if (type == 2) {
      // 簿记下达
      params.method = '0';
      // 簿记单独处理
      this.saveOrderNew(params);
      return;
    }
    // 新增指令  组合试算  薄记下达
    const url = type == 1 ? 'assetsOrderM/orderSave' : type == 11 ? 'portfolioTrialAddM/zcglPlanSave' : 'assetsOrderM/tradeBookSave';

    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (msg) => {
        if (msg) {
          if (type == 2 || type == 11) {
            // 簿记下达成功
            this.props && this.props.onOk && this.props.onOk();
            this.onCancel(); // 初始化form表单
          } else {
            // 指令下达成功
            this.onCancel(); // 初始化form表单
            this.handleCancel(); // 关闭模态框
          }
        }
        if (this.props.type == 1) {
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        }
      },
    });
  };

  // 簿记下达
  saveOrderNew = (args) => {
    const { type } = this.props;
    const { productCode, productName, portfolioCode, portfolioName } = this.state;
    if (type == 2) {
      const params = {
        productCode, // 产品code
        productId: args.productid, // 产品id
        productName, // 产品名称
        portfolioCode, // 组合code
        portfolioId: args.portfolioid, // 组合id
        portfolioName, // 组合名称
        tradingCode: args.tradingcode, // 证券代码
        tradingName: args.secuabbr, // 证券名称
        exchangeCode: args.exchangeCode, // 交易市场
        tradeDir: args.direction, // 交易方向
        price: args.price, // 价格
        num: args.amount, // 数量
        amount: args.parValueTotal, // 交易总额
        investmentType: args.investmentType, // 投资类型
        remark: args.remark, // 备注
        instructionType: '0', // 0是指簿记
      };
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(type, undefined, undefined, undefined, () => {
          console.log('自动交收');
          this.setState({
            orderParams: params,
            visibleStep: true,
          });
        })
      ) {
        return;
      }
      // 没有自动交收
      this.setState({
        orderParams: params,
        visibleStep: true,
      });
    }
  };

  // 下达成功之后  清空页面
  handleSuccess = () => {
    this.setState({
      visibleStep: false,
    });
    // 恢复默认状态
    this.onCancel();
  };

  // 下达失败 用户主动点击关闭 处理逻辑
  handleError = (type) => {
    this.setState({
      visibleStep: false,
    });
    if (type) {
      // 更新可用持仓 还是可用资金
      this.props.changeTimeStamp(type == 1 ? 'timeStamp1' : 'timeStamp2');
    }
  };

  // 二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };

  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading, type } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 700,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['assetsOrderM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        <OrderFormC type={'3'} info={querys} />
      </ModalC>
    );
  };

  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        // 校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };

  // 试算按钮点击
  trialOnClick = () => {
    const {
      type,
      user: { currentUser },
    } = this.props;
    const data = this.orderForm.getInfo();
    // 校验页面数据
    if (!data) return;
    const obj = {};
    obj.type = 20;
    obj.productCode = this.state.productId; // 产品code
    obj.portfolioCode = this.state.portfolioCode; // 组合code
    obj.tenant = currentUser.tenant; // 租户code
    obj.businessType = '20';
    obj.type = '20';
    obj.trade20 = { ...data };
    this.setState({ trailModel: true }, () => {
      this.props.dispatch({
        type: 'trailM/trialData',
        payload: obj,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };

  // 试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key === 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };

  // 试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  // 获取组合code
  portfolioOnChange = (e) => {
    this.props.portfolioOnChange(e?.key);
    // if (this.props.type == '1') this.queryIsAccountConfigured(e);//指令下达的时候进行校验组合是否配置
    if (e) {
      this.setState({ portfolioId: e?.key, portfolioCode: e?.info?.portfolioCode, portfolioName: e?.info?.portfolioName });
    } else this.setState({ portfolioId: undefined, portfolioCode: undefined, portfolioName: undefined });
    this.props.onChangePortfolioCode(e?.info?.portfolioCode);
  };

  // 获取产品code
  productOnChange = (e) => {
    if (e) {
      this.setState({ productId: e?.info?.portfolioCode, productName: e?.info?.portfolioName, productCode: e?.info?.portfolioCode });
    } else this.setState({ productId: undefined, productName: undefined, productCode: undefined });
  };

  render() {
    const { loading, type, endDate, startDate } = this.props;
    const { visibleStep, orderParams } = this.state;
    return (
      <div>
        <div>
          <OrderFormC
            type={type} // 1-指令新增   2-簿记新增    3-详情  4-交收  11-组合试算
            info={this.props.info} // type=3 || 4时，需回填字段
            onRef={(ref) => {
              this.orderForm = ref;
            }}
            tradingOnChange={this.props.tradingOnChange} // 证券代码变更事件
            portfolioOnChange={this.portfolioOnChange} // 组合变更拿值
            productOnChange={this.productOnChange} // 产品变更事件
            investmentType={this.props.position.investmentType}
            position={this.props.position}
            money={this.props.money}
            endDate={endDate}
            startDate={startDate}
          />
        </div>
        <div style={{ marginTop: '20px' }} className={style.btnOperate}>
          <PrimaryC loading={loading.effects['assetsOrderM/tradeBookSave'] === true} onClick={this.onOk} title={this.props.type == 1 ? '下达' : '确定'} />
          <PrimaryGhostC onClick={this.onCancel} title='取消' style={{ marginLeft: '16px' }} />
        </div>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        {this.state.trailModel && this.showTrail()}
        {visibleStep ? <OrderC visible={visibleStep} handleSuccess={this.handleSuccess} handleError={this.handleError} params={orderParams} tradeType={'assetBj'} /> : null}
      </div>
    );
  }
}
export default connect(({ assetsOrderM, userM: user, loading, trailM, isAccountConfiguredM }) => ({
  assetsOrderM,
  user,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
}))(Form.create()(AddOrderC));
